# -*- coding: utf-8 -*-
from scapy.all import *
import os
from calcEntropy import PcapFeatures
import statistics


def read_pcap(file_name):
    print('开始读取pcap')
    file_data = rdpcap(file_name)
    print('读取完成')
    return file_data


def fenliu(file_data):
    port = []
    l = len(file_data)
    for i in range(0, l):
        try:
            # syn包的tcp标志位为0x02,跟据syn包先将源端口组成列表，返回port列表
            if file_data[i]['TCP'].flags == 0x02:
                port.append(file_data[i]['TCP'].sport)
        except:
            pass
    return port


def fenbao(file_data):
    port = fenliu(file_data)
    l1 = len(port)
    data_list = [[] for _ in range(l1)]
    #data_list=[[]]*l1  不能这样创建多维列表，会出问题，应该用上面的方式
    l = len(file_data)
    for i in range(0, l):
        try:
            #源端口在port列表里，则端口获取在列表中的索引，放入对应的data_list中
            if file_data[i]['TCP'].sport in port:
                j = port.index(file_data[i]['TCP'].sport)
                data_list[j].append(file_data[i])
            # 目的端口在port列表里，则端口获取在列表中的索引，放入对应的data_list中
            elif file_data[i]['TCP'].dport in port:
                j = port.index(file_data[i]['TCP'].dport)
                data_list[j].append(file_data[i])
        except:
            pass
    return data_list


def save_file(dir, data_list):
    xiaobao = []
    file_name = []
    l = len(data_list)
    print('开始保存pcap,共有' + str(l) + '个pcap包')
    for i in range(0, l):
        name = dir + 'ips' + str(i) + '.pcap'
        wrpcap(name, data_list[i])
        xiaobao.append(name)
        file_name.append('ips' + str(i))
    print('保存完成')
    return xiaobao,file_name,l


if __name__ == "__main__":
    dir_name = os.path.dirname(__file__) + '/'
    #file_name = dir_name + "ss4.0.7.pcap"
    #file_name = dir_name + "http2.pcap"
    file_name = dir_name + "https1.pcap"
    #file_name = dir_name + "ss5-3.4.4.pcap"
    file_data = read_pcap(file_name)
    data = fenbao(file_data)
    xiaobao,file_name,l = save_file(dir_name, data)
    i = 0
    templist = []
    sum = 0
    for file_path in xiaobao:
        pcap_feat = PcapFeatures(file_path)
        # os.remove(file_path)
        b = pcap_feat.getHttp_S_ReqEntropy()
        if (len(b) >= 1):
            templist = templist + b
        #print(b)
        tempi = 10  #N截断的N
        if len(b) > 0:
            pingjun = statistics.mean(b[:tempi])
            # print("num", i, pingjun)
            if pingjun < 5.24916179173597 or pingjun > 6.212293999527468:
                sum += 1
                print(file_name[i])
        '''
        if len(b) > 1:
            pingjun = statistics.mean(b)
            #print("num", i, pingjun)
        elif len(b) == 1:
            pingjun = b[0]
            #print("num", i, pingjun)
        '''
        os.remove(file_path)
        i = i + 1
    pingjun = statistics.mean(templist)
    fangcha = statistics.stdev(templist)
    lower_bound = pingjun - 2 * fangcha
    upper_bound = pingjun + 2 * fangcha
    # print(lower_bound, upper_bound)  #输出ss流量的2倍置信区间，非ss请注释
    print('filter proportion:',str(float(sum)/l*100),'%')
